package com.power.ding;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.Enumeration;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Component;

import com.plf.common.servlet.RequestParameterWrapper;

import lombok.extern.slf4j.Slf4j;

@Component
@Slf4j
public class RequestLoggingFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        RequestParameterWrapper cloneRequest=new RequestParameterWrapper(httpRequest);
        log.info("------------------");
        log.info("收到请求 {} {}", cloneRequest.getMethod(), cloneRequest.getRequestURI());
        
        if(cloneRequest.getMethod().equalsIgnoreCase("OPTIONS")) {
            chain.doFilter(request, response);
            return;
        }
        
        log.info("Headers:");
        Enumeration<String> headerNames = cloneRequest.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String headerName = headerNames.nextElement();
            log.info("\t"+headerName + ": " + cloneRequest.getHeader(headerName));
        }

        log.info("Parameters:");
        Enumeration<String> parameterNames = cloneRequest.getParameterNames();
        while (parameterNames.hasMoreElements()) {
            String paramName = parameterNames.nextElement();
            log.info("\t"+paramName + ": " + cloneRequest.getParameter(paramName));
        }

        log.info("Body:");
        StringBuilder stringBuilder = new StringBuilder();
        String line;
        try (BufferedReader reader = cloneRequest.getReader()) {
            while ((line = reader.readLine()) != null) {
                stringBuilder.append(line);
            }
        }
        log.info(stringBuilder.toString());
        log.info("=====================");

        // 继续执行过滤器链
        chain.doFilter(request, response);
    }
}